# -*- coding:utf-8 -*-

import uvicorn
from typing import Callable
from fastapi import FastAPI
from contextlib import asynccontextmanager

from app.config import settings
from core.database import register_db, init_db
from core.database.redis import redis_connect, RedisConfig

@asynccontextmanager
async def lifespan(app: FastAPI):
    print("FastAPI 启动中")
    
    app.state.redis = await redis_connect(
        RedisConfig(settings.REDIS_HOST, settings.REDIS_PORT, settings.REDIS_PASSWORD, settings.REDIS_DB, settings.REDIS_DECODE_RESPONSES, settings.REDIS_ENCODING))
    await register_db(settings.DB_DSN)
    await init_db()
    yield print("FastAPI 已启动")
    await app.state.redis.close()
    print("FastAPI 已停止")



def startup(app: FastAPI)-> Callable:
    async def app_start()->None:
        print("FastAPI 已启动")
        await register_db(f"mysql+pymysql://{settings.DB_USER}:{settings.DB_PASSWORD}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}")
    return app_start

# app.add_event_handler("startup", startup(app))
# app.add_event_handler("shutdown", events.stopping(app))
